package app.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import app.annotation.RequestPlanAnnotation;
import app.controller.BookController;
import app.model.sys.CmdbRequestPlanLog;
import app.repository.sys.RequestPlanLogRepository;

/**
 * @author shishun.wang
 * @date 下午3:58:05 2016年5月4日
 * @version 1.0
 * @describe 
 */
@Component
public class SessionHandlerInterceptor implements HandlerInterceptor {
	
	private static Logger logger = LoggerFactory.getLogger(BookController.class);

	@Autowired
	private RequestPlanLogRepository requestPlanLogRepository;
	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HandlerMethod method = (HandlerMethod)handler;
		System.out.println(method.getMethod().getName());
		RequestPlanAnnotation annotation = method.getMethod().getAnnotation(RequestPlanAnnotation.class);
		if(null != annotation){
			logger.debug(annotation.title());
			System.out.println("---------------->preHandle:["+annotation.title()+"]");
			CmdbRequestPlanLog requestPlanLog = new CmdbRequestPlanLog();
			{
				requestPlanLog.setTitle(annotation.title());
				requestPlanLog.setContent(annotation.content());
				requestPlanLog.setRemoteIpAddress("127.0.0.1");
				requestPlanLog.setRequestUrl(request.getServletPath());
				requestPlanLog.setRequestParameter(request.getParameterMap().toString());
			}
			
			requestPlanLogRepository.save(requestPlanLog);
		}
		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("---------------->postHandle");
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("---------------->afterCompletion");
	}

}
